package com.conversationboard.controller;

import java.io.IOException;
import java.sql.SQLException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.conversationboard.controller.debug.ServletDebugInfo;
import com.conversationboard.logger.Logger;
import com.conversationboard.model.Message;
import com.conversationboard.model.NoSuchThreadException;
import com.conversationboard.model.Thread;
import com.conversationboard.model.User;
import com.conversationboard.security.EncryptedKey;
import com.conversationboard.security.EncryptionException;

@WebServlet(name = "AdminUpdateMessageControllerServlet", urlPatterns = "/Admin/AdminUpdateMessageControllerServlet")
public class AdminUpdateMessageControllerServlet extends HttpServlet {

	private static final long serialVersionUID = 1023255953086944436L;


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");

		/*
		 * Pick up the board, thread and message IDs from the HTTP GET
		 * parameters, update the message in the database and the cache, and
		 * forward to success message
		 */

		String boardId = (String) request.getParameter("boardId");
		int boardIdNumber = Integer.parseInt(boardId);

		String threadId = (String) request.getParameter("threadId");
		int threadIdNumber = Integer.parseInt(threadId);

		String messageId = (String) request.getParameter("messageId");
		int messageIdNumber = Integer.parseInt(messageId);

		String body = (String) request.getParameter("text");

		try {

			/* Is user authorised? */

			User user = User.get(request.getUserPrincipal().getName());

			String key = request.getParameter("key");
			EncryptedKey encryptedKey = new EncryptedKey();

			if (!encryptedKey.isValid(key, user.getLoginId())) {
				Logger.log(new Date(), "Part 1 of error: " + this.getClass().getName(), user);
				String postRequest = ServletDebugInfo.getRawRequest(request);
				Logger.log(new Date(), "Part 2 of error:\n\n" + postRequest, user);
				return;
			}

			Thread thread = Thread.get(boardIdNumber, threadIdNumber);
			Message message = thread.getMessage(messageIdNumber);

			/* Change the message to reflect the update (in the cache) */
			message.setBody(body);

			/* Update the database */
			Message.edit(user, message);

			response.sendRedirect(request.getContextPath() + "/ThreadSelectedControllerServlet?boardid=" + boardId + "&threadid=" + threadId);

		} catch (NoSuchThreadException e) {
			throw new ServletException(e);
		} catch (SQLException e) {
			throw new ServletException(e);
		} catch (EncryptionException e) {
			throw new ServletException(e);
		}
	}

}
